package com.laopan.wxpay.request.query;

import com.laopan.wxpay.bean.OrderMch;
import com.laopan.wxpay.bean.result.OrderResult;
import com.laopan.wxpay.config.WxPayConfig;
import com.laopan.wxpay.exception.OrderNotExistException;
import com.laopan.wxpay.exception.WxPayException;
import com.laopan.wxpay.request.RequestCallback;
import com.laopan.wxpay.request.WxPayRequest;
import com.laopan.wxpay.utils.JsonUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;

/**
 * @author laopan
 * @date 2021/4/5 0005 21:46
 */
public class RealQueryOrder extends WxPayRequest<OrderMch, OrderResult> {

    private final static Logger log = LoggerFactory.getLogger(MchOrderIdQuery.class);

    public RealQueryOrder(WxPayConfig wxPayConfig) {
        super(wxPayConfig);
    }

    @Override
    protected Class<OrderResult> getResultClass() {
        return OrderResult.class;
    }

    public OrderResult query(String mchId, String id, String path) throws WxPayException {
        return query(mchId, id, path, response -> {
            OrderResult result = new OrderResult();
            int code = response.getStatusLine().getStatusCode();
            if (code == HttpStatus.SC_OK) {
                HttpEntity entity = response.getEntity();
                try {
                    String resultStr = EntityUtils.toString(entity);
                    return JsonUtils.fromJson(resultStr, OrderResult.class);
                } catch (IOException e) {
                    log.error("订单查询失败", e);
                }
            } else if (code == HttpStatus.SC_NOT_FOUND) {
                throw new OrderNotExistException();
            }
            return null;
        });
    }

    public OrderResult query(String mchId, String id, String path, RequestCallback<OrderResult> requestCallback) throws WxPayException {
        return super.get(path + id, new OrderMch(mchId), requestCallback);
    }
}
